package com.elt.image.util;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.widget.ImageView;

/**
 * 
 * @author abu
 * 
 */
public final class BitMapUtil {

	public static Bitmap setBitmapOption(byte[] data, int width, int height) {
		BitmapFactory.Options result = new BitmapFactory.Options();
		result.inJustDecodeBounds = true;
		// byte[] data = getBytes(is);
		BitmapFactory.decodeByteArray(data, 0, data.length, result);
		int outWidth = result.outWidth;
		int outHeight = result.outHeight;
		int simpleSize = 1;
		if (width != 0 && height != 0) {
			if (outWidth > width || outHeight > height) {
				final int heightRatio = Math.round((float) outHeight
						/ (float) height);
				final int widthRatio = Math.round((float) outWidth
						/ (float) width);
				simpleSize = heightRatio < widthRatio ? heightRatio
						: widthRatio;
			}
		}

		result.inSampleSize = simpleSize;
		result.inJustDecodeBounds = false;
		result.inPreferredConfig = Bitmap.Config.RGB_565;
		result.inPurgeable = true;
		result.inInputShareable = true;
		return BitmapFactory.decodeByteArray(data, 0, data.length, result);
	}

	public static String bitmapToString(Bitmap bm) {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		bm.compress(Bitmap.CompressFormat.PNG, 60, baos);
		byte[] b = baos.toByteArray();
		return new String(b);
	}

	public static byte[] getBytes(InputStream is) throws IOException {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		byte[] b = new byte[1024];
		int len = 0;
		while ((len = is.read(b, 0, 1024)) != -1) {
			baos.write(b, 0, len);
			baos.flush();
		}
		byte[] bytes = baos.toByteArray();
		return bytes;
	}

	public static Bitmap getImageViewBitmap(ImageView imgView) {

		Bitmap bitmap = null;

		if (imgView == null) {
			return bitmap;
		}
		Drawable drawable = imgView.getDrawable();

		if (drawable != null) {
			if (drawable instanceof BitmapDrawable) {
				BitmapDrawable bd = (BitmapDrawable) drawable;
				bitmap = bd.getBitmap();
			}
		}
		return bitmap;
	}

	public static void recycleImageViewBitMap(ImageView imageView) {
		if (imageView != null) {
			BitmapDrawable bd = (BitmapDrawable) imageView.getDrawable();
			rceycleBitmapDrawable(bd);
		}
	}

	private static void rceycleBitmapDrawable(BitmapDrawable bd) {
		if (bd != null) {
			Bitmap bitmap = bd.getBitmap();
			rceycleBitmap(bitmap);
		}
		bd = null;
	}

	private static void rceycleBitmap(Bitmap bitmap) {
		if (bitmap != null && !bitmap.isRecycled()) {
			bitmap.recycle();
			bitmap = null;
		}
	}
}
